package com.yxq.mdt.app.modules.splash.ui;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;

import com.orhanobut.hawk.Hawk;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.yxq.mdt.app.R;
import com.yxq.mdt.app.base.BaseActivity;
import com.yxq.mdt.app.base.CustomClickListener;
import com.yxq.mdt.app.constant.Constant;
import com.yxq.mdt.app.constant.SPKey;
import com.yxq.mdt.app.dialog.CostumerDialog;
import com.yxq.mdt.app.modules.login.bean.UserBean;
import com.yxq.mdt.app.modules.login.ui.LoginActivity;
import com.yxq.mdt.app.modules.main.bean.NameAndPhoneBean;
import com.yxq.mdt.app.modules.main.ui.MainActivity;
import com.yxq.mdt.app.modules.splash.model.SplashModel;
import com.yxq.mdt.app.modules.splash.presenter.ISplashContract;
import com.yxq.mdt.app.modules.splash.presenter.SplashPresenter;

/**
 * @author L
 * @time
 * @describe 启动页
 */
public class SplashActivity extends BaseActivity<SplashPresenter> implements ISplashContract.View {

    private Handler mHandler = new Handler();
    private RxPermissions rxPermissions;
    /**
     * 读写权限  自己可以添加需要判断的权限
     */
    public static String[] permissions = {Manifest.permission.READ_PHONE_STATE, Manifest.permission.WRITE_EXTERNAL_STORAGE};

    public boolean checkPermission3(Context context, String[] permissions) {

        for (String permission : permissions) {
            int per = ContextCompat.checkSelfPermission(context, permission);
            if (PackageManager.PERMISSION_GRANTED != per) {
                return false;
            }
        }
        return true;
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_splash;
    }

    @Override
    public void initView() {
        mPresenter = new SplashPresenter(this, new SplashModel());
        rxPermissions = new RxPermissions(this);
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        handlePermissionLogic();
    }

    private void checkPermission() {
        if ((PackageManager.PERMISSION_GRANTED == ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE))
                && (PackageManager.PERMISSION_GRANTED == ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE))) {
            if (mPermissionDialog != null) {
                mPermissionDialog.dismiss();
            }
            handleSplashLogic();
        }
    }

    @SuppressLint("CheckResult")
    private void handlePermissionLogic() {

        if (checkPermission3(SplashActivity.this, permissions)) {
            handleSplashLogic();
        } else {
            requestPermissions();
        }
    }

    private void gotoLoginActivity() {
        Intent intent;
        if (Constant.getFirstInstall()) {
            //第一次安装，跳转引导页
            intent = new Intent(mActivity, GuideActivity.class);
            intent.putExtra("type", 1);
        } else {
            intent = new Intent(this, LoginActivity.class);
        }
        startActivity(intent);
        finish();
    }

    private void gotoMainActivity() {
        new Handler().postDelayed(() -> {
            Intent intent;
            if (Constant.getFirstInstall()) {
                //第一次安装，跳转引导页
                intent = new Intent(mActivity, GuideActivity.class);
                intent.putExtra("type", 2);
            } else {
                //跳转主页
                intent = new Intent(mActivity, MainActivity.class);
            }
            startActivity(intent);
            finish();
        }, 500);
    }


    /**
     * 请求权限
     */
    @SuppressLint({"CheckResult", "AutoDispose"})
    private void requestPermissions() {
        rxPermissions.request(permissions).subscribe(permission -> {
            Hawk.put(SPKey.SP_KEY_IS_FIRST_USE, false);
            if (permission) {
                // 用户同意所有权限
                handleSplashLogic();
            } else {
                showConfirmDialog("为了您正常使用,需要使用手机存储权限和电话权限.", new CustomClickListener() {
                    @Override
                    public void onSingleClick() {
                        gotoPermissionManager();
                    }
                }, new CustomClickListener() {
                    @Override
                    public void onSingleClick() {
                        finish();
                    }
                });
            }
        });
    }

    private void handleSplashLogic() {
        if (mPresenter == null) {
            mPresenter = new SplashPresenter(this, new SplashModel());
        }

        //先获取配置信息
        mPresenter.getUserInfo();
        return;

//        UserBean userBean = Hawk.get(SPKey.SP_KEY_USER_INFO);
//        if (userBean == null) {
//            gotoLoginActivity();
//        } else {
//            gotoMainActivity();
//        }
    }

    private CostumerDialog mPermissionDialog;

    /**
     * 显示对话框
     */
    public void showConfirmDialog(@NonNull String context, @NonNull View.OnClickListener sureListener, @NonNull View.OnClickListener cancelListener) {

        if (mPermissionDialog == null) {
            mPermissionDialog = new CostumerDialog.Builder(this, R.style.custom_dialog_no_match)
                    .setContentView(R.layout.dialog_confirm_cancel_layout)
                    .setCancelable(false)
                    .create();
        }

        TextView title = mPermissionDialog.findViewById(R.id.tv_title);
        title.setText("授权提示");

        TextView content = mPermissionDialog.findViewById(R.id.tv_content);
        content.setText(context);

        //确定
        TextView sure = mPermissionDialog.findViewById(R.id.tv_sure);
        sure.setOnClickListener(v -> {
            sureListener.onClick(v);
        });

        //取消
        TextView cancel = mPermissionDialog.findViewById(R.id.tv_cancel);
        cancel.setOnClickListener(v -> {
            mPermissionDialog.dismiss();
            cancelListener.onClick(v);
        });
        mPermissionDialog.show();
    }

    @Override
    public void onLoadNameAndPhoneSuccess(NameAndPhoneBean nameAndPhoneBean) {
        if (nameAndPhoneBean != null) {
            Hawk.delete(SPKey.SP_KEY_NAME_PHONE_INFO);
            Hawk.put(SPKey.SP_KEY_NAME_PHONE_INFO, nameAndPhoneBean);
        }
        mHandler.postDelayed(() -> {
            UserBean userBean = Hawk.get(SPKey.SP_KEY_USER_INFO);
            if (userBean == null) {
                gotoLoginActivity();
            } else {
                gotoMainActivity();
            }
        }, 500);
    }

    @Override
    public void onLoadNameAndPhoneFailed(String err) {
//        Hawk.delete(SPKey.SP_KEY_NAME_PHONE_INFO);

        UserBean userBean = Hawk.get(SPKey.SP_KEY_USER_INFO);
        if (userBean == null) {
            gotoLoginActivity();
        } else {
            gotoMainActivity();
        }

    }
}
